<template>
  <el-container style="height: 100%; padding: 10px 10px 0" :class="{ disabled: disableAction }">
    <el-aside width="200px" style="background-color: white; margin: 0; padding: 0">
      <el-form size="mini" @submit.native.prevent>
        <el-form-item>
          <header-select class="project-box" @selectProject="onSelectProject" style="line-height: normal" />
        </el-form-item>
      </el-form>
      <div class="aside-list">
        <div class="item ellipsis" v-for="item in businessTypeList" :key="item.value" :title="item.label" :class="{ active: item.value === queryParams.businessType }" @click="onBusinessType(item)">
          <svg-icon :icon-class="item.icon" v-if="item.icon" />
          {{ item.label }}
        </div>
      </div>
    </el-aside>
    <el-main style="padding: 0 0 0 20px">
      <el-form ref="queryForm" :model="queryParams" size="mini" inline @submit.native.prevent style="white-space: nowrap; overflow-x: auto">
        <el-form-item label="选择日期">
          <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-breadcrumb class="folder-paths" separator="/">
        <el-breadcrumb-item>
          <span v-if="!folderPaths.length">主目录</span>
          <a @click="switchFolder({ action: 'main' })" v-else>主目录</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item, index) in showFolderPaths" :key="index">
          <span v-if="item.fid === undefined">{{ item.showFileName }}</span>
          <a @click="switchFolder(item)" :title="item.fileName" v-else>{{ item.showFileName }}</a>
        </el-breadcrumb-item>
      </el-breadcrumb>

      <div style="position: relative">
        <el-popover placement="right" trigger="hover">
          <i slot="reference" class="el-icon-question pointer operation-tip" />
          <div>1. 双击 <svg-icon icon-class="folder" /> 打开文件夹</div>
          <div>2. 在文件上右键可进行更多操作</div>
        </el-popover>
      </div>

      <div class="folder-list" v-loading="listLoading" element-loading-background="rgba(255, 255, 255, 0.5)">
        <FolderList :list="list" @openFolder="openFolder" />
      </div>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-main>
  </el-container>
</template>
<script>
import moment from 'moment'
import { debounce } from '@/utils'
import { imageTypes, videoTypes } from '@/utils/baseData'
import { getFileURL } from '@/api/common'
import { getProjectAlbum } from '@/api/baseManage/projectAlbum'
import HeaderSelect from '@/views/patrol/components/HeaderSelect'
import FolderList from './components/FolderList'
// 业务类型
const businessTypeList = [
  { label: '平面图', value: 'PROGRAPH', ftype: 'FILE_TYPE', icon: 'picture' },
  { label: '关键工序', value: 'KEYTABLE', ftype: 'KEYTABLE', icon: 'nested' },
  { label: '过程检查', value: 'PROCESS', ftype: 'PROCESS', icon: 'number' },
  { label: '交付/售后/展示区检查', value: 'CHKSCORE', ftype: 'EVAL_CHKITEM', icon: 'deliver' },
  { label: '巡检记录仪', value: 'RECORDER', ftype: 'RECORDER', icon: 'ico_camera' }
]
export default {
  name: 'ProjectAlbum',
  components: { HeaderSelect, FolderList },
  data() {
    const startTime = moment().startOf('year').format('YYYY-MM-DD')
    const endTime = moment().format('YYYY-MM-DD')
    return {
      businessTypeList,
      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: '',
        businessType: businessTypeList[0].value
      },
      dateRange: [startTime, endTime],
      folderPaths: [] // 文件夹目录
    }
  },
  computed: {
    disableAction() {
      return this.listLoading
    },
    currFolderId() {
      const list = this.folderPaths
      if (!list.length) return ''

      const last = list[list.length - 1]
      return last?.fid || ''
    },
    // 展示的目录
    showFolderPaths() {
      const list = JSON.parse(JSON.stringify(this.folderPaths))
      // 目录超过4级只显示最后3级
      if (list.length > 3) list.splice(0, list.length - 3, { showFileName: '...' })
      return list
    }
  },
  watch: {
    currFolderId() {
      this.handleQueryDebounce()
    }
  },
  created() {
    this.handleQueryDebounce = debounce(this.handleQuery, 100)
  },
  methods: {
    onSelectProject(project) {
      const projectId = project?.id || ''
      this.queryParams.projectId = projectId
      this.queryParams.businessType = businessTypeList[0].value
      this.folderPaths = []
      if (projectId) this.handleQuery()
    },
    onBusinessType(item) {
      this.queryParams.businessType = item.value
      this.folderPaths = []
      this.handleQueryDebounce()
    },
    async getList() {
      const { dateRange } = this
      const opt = { ...this.queryParams }
      if (!opt.projectId) return (this.list = []) && this.msgError('请选择项目')
      if (!opt.businessType) return (this.list = []) && this.msgError('请选择左侧业务类型')

      if (Array.isArray(dateRange) && dateRange.length === 2) {
        opt.startTime = dateRange[0]
        opt.endTime = dateRange[1]
      }

      if (this.currFolderId) {
        const list = this.folderPaths
        const last = list[list.length - 1]
        opt.parentId = list.map(i => i.fid).join(',')
        opt.ftype = last.ftype
      } else {
        const item = businessTypeList.find(i => i.value === opt.businessType)
        opt.ftype = item.ftype
      }

      this.listLoading = true
      const res = await getProjectAlbum(opt).catch(() => false)
      this.listLoading = false
      if (res === false) {
        this.list = []
        return (this.total = 0)
      }

      const data = res.rows || []
      data.map(i => {
        // 用于文件详情时入参
        i.ancestorIds = opt.parentId

        i.isFolder = !i.isFile
        i.fileName = i.displayName || ''
        if (i.isFolder) {
          // 处理文件夹名过长
          const name = i.fileName || ''
          i.showFileName = name.length > 20 ? `...${name.slice(-8)}` : name
          return
        }

        i.fileId = i.fid
        i.url = getFileURL(i.fileId)

        if (!i.fileType) return
        i.fileName = i.fileName || `${i.fileId}.${i.fileType}`
        if (imageTypes.includes(i.fileType)) i.isImage = true
        else if (videoTypes.includes(i.fileType)) i.isVideo = true
      })
      // 文件夹前置
      data.sort((a, b) => b.isFolder - a.isFolder)
      this.list = data
      this.total = res.total || 0
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    switchFolder(item) {
      // 返回主目录
      if (item.action === 'main') {
        this.folderPaths = []
        return this.handleQueryDebounce()
      }
      // 最后一级
      if (item.fid === this.currFolderId) return
      // 移除子层级
      const index = this.folderPaths.findIndex(i => i.fid === item.fid)
      this.folderPaths.splice(index + 1)
    },
    openFolder(item) {
      if (!item.fid || item.fid === this.currFolderId) return
      this.folderPaths.push(item)
    }
  }
}
</script>
<style lang="scss" scoped>
.project-box /deep/ .project-name {
  width: 134px;
}
.aside-list {
  height: calc(100% - 50px);
  overflow: auto;
  font-size: 12px;
  color: #606266;
  border: 1px solid #ebebeb;
  border-radius: 6px;
  .item {
    padding: 0 10px;
    cursor: pointer;
    &:hover {
      background-color: #f5f7fa;
    }
    &.active {
      background-color: #409eff;
      color: #fff;
      font-weight: bold;
    }
  }
}
.folder-paths {
  min-width: 600px;
  font-size: 12px;
  background: linear-gradient(90deg, #f5f7fa, rgba(#f5f7fa, 0));
  padding: 8px 10px;
  margin-bottom: 12px;
  user-select: none;
}
.operation-tip {
  position: absolute;
  top: -20px;
  right: 0;
  color: #606266;
}
.folder-list {
  min-width: 600px;
  min-height: 300px;
  max-height: calc(100% - 150px);
  overflow-y: auto;
  border: 1px solid #ebebeb;
  border-radius: 6px;
  padding: 15px;
}
</style>
